package com.stars.easyms.schedule.factory;

import org.apache.http.Header;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * Rest模板工厂类
 *
 * @author guoguifang
 */
public class RestTemplateFactory {

    private static RestTemplate restTemplate;

    public static RestTemplate getRestTemplate() {
        if (restTemplate == null) {
            synchronized (RestTemplateFactory.class) {
                if (restTemplate == null) {
                    restTemplate = new RestTemplate(clientHttpRequestFactory());
                    restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
                    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
                    messageConverters.add(new MappingJackson2HttpMessageConverter());
                    restTemplate.setMessageConverters(messageConverters);
                }
            }
        }
        return restTemplate;
    }

    private static ClientHttpRequestFactory clientHttpRequestFactory() {
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        //整个连接池的并发
        poolingHttpClientConnectionManager.setMaxTotal(1000);
        //每个主机的并发
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(1000);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
        //开机重启
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
        //默认的头信息
        List<Header> headerList = new ArrayList<>();
        headerList.add(new BasicHeader("Accept", "application/json"));
        headerList.add(new BasicHeader("Accept-Charset", "UTF-8"));
        headerList.add(new BasicHeader("Content-Type", "application/json"));
        httpClientBuilder.setDefaultHeaders(headerList);
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
        //连接超时时间，毫秒
        clientHttpRequestFactory.setConnectTimeout(5000);
        //读写超时时间，毫秒
        clientHttpRequestFactory.setReadTimeout(600000);
        return clientHttpRequestFactory;
    }
}
